<template>
	<view class="checkout-page">
		<u-subsection v-if='!isPoint' :list="list" :current="current" @change='changeCurrent'></u-subsection>
		<!-- 地址选择 -->
		<view v-if='current == 0' class="address-card" @click="chooseAddress">
			<view v-if="!selectedAddress" class="empty-address">
				<uni-icons type="location-filled" size="24"></uni-icons>
				<text>请选择收货地址</text>
			</view>
			<view v-else class="address-info">
				<view class="address-header">
					<text>{{selectedAddress.userName}}</text>
					<text>{{selectedAddress.telNumber}}</text>
				</view>
				<text class="address-detail">
					{{selectedAddress.provinceName}}{{selectedAddress.cityName}}{{selectedAddress.countyName}}{{selectedAddress.detailInfo}}
				</text>
			</view>
			<uni-icons type="arrowright" size="20"></uni-icons>
		</view>
		<view v-else style='color:#909399;padding:20px;font-size:14px;'>
			<view>选择寄存的客户我们会将您购买的产品寄存到我们专用的仓库，您可以在我的仓库里面查看，并且可以用作定制礼品</view>
		</view>
		<view style='padding:0px 20px;'>
			<u--textarea v-model="comment" placeholder="订单备注"></u--textarea>
		</view>
		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="section-title">商品清单</view>
			<view class="goods-list">
				<view v-for="(item,index) in orderItems" :key="index" class="goods-item">
					<image :src="item.cover" mode="aspectFill" class="goods-image"></image>
					<view class="goods-info">
						<text class="goods-name">{{item.specification.product.__toString}}</text>
						<text class="goods-spec">{{item.specification.name}}</text>
						<view class="goods-bottom">
							<text v-if='isPoint'
								class="goods-price">{{(parseFloat(item.price)/pointRate).toFixed(2)}}积分</text>
							<text v-else class="goods-price">
								￥{{item.price}}
							</text>
							<text class="goods-quantity">x{{item.quantity}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>


		<!-- 价格明细 -->
		<view class="price-section">
			<view class="price-row">
				<text>商品总价</text>
				<text v-if='isPoint'>{{(totalPrice/pointRate).toFixed(2)}}积分</text>
				<text v-else>￥{{actualPrice.toFixed(2)}}</text>
			</view>
			<!-- <view class="price-row total">
				<text>实付款</text>
				<text class="price-total">¥{{actualPrice.toFixed(2)}}</text>
			</view> -->
		</view>
		<u-line></u-line>
		<view v-if='isPoint' style='padding:10px'>
			<u-radio-group v-model="payType" placement="column">
				<u-radio key="point" name="point">
					<view @click="payType= 'point'">积分兑换(￥{{point}})</view>
				</u-radio>
			</u-radio-group>
		</view>
		<view v-else style='padding:10px'>
			<u-radio-group v-model="payType" placement="column" activeColor='green'>
				<u-radio :customStyle="{marginBottom: '8px'}" key="wechat" label='微信支付' name="wechat">
					<view @click='payType = "wechat"'>微信支付</view>
				</u-radio>
				<u-radio :customStyle="{marginBottom: '8px'}" key="balance" label='余额支付' name="balance">
					<view @click='payType = "balance"'>余额支付(￥{{amount}})</view>
				</u-radio>
			</u-radio-group>
		</view>
		<u-line></u-line>
		<!-- 支付按钮 -->
		<view class="footer">
			<view style='padding:10px'>
				<u-button :text='isPoint ? "确定兑换" : "支付订单"' type='success' shape='circle'
					@click='createOrder'></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import wechatPay from '@/utils/wechat-pay.js'
	export default {
		data() {
			return {
				selectedAddress: '',
				show: false,
				goodsList: [],
				availableCoupons: [],
				selectedCoupon: '',
				choosedCoupon: '',
				comment: '',
				totalPrice: 0,
				actualPrice: 0,
				discount: 0,
				orderItems: [],
				point: 0,
				usePoint: true,
				pointRate: 0,
				pointDiscount: 0,
				pointPaid: 0,
				list: ['邮寄'],
				current: 0,
				isPoint: false,
				amount: 0,
				payType: 'wechat'
			}
		},
		onShow() {
			this.goodsList = uni.getStorageSync('orderCarts')
			console.log('orderCart', this.goodsList)
			if (this.goodsList == '' || this.goodsList.length == 0) {
				uni.showModal({
					title: '',
					content: '暂无购买产品！',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
				return
			}
			// 查第一个产品，看是积分兑换还是普通产品
			this.request.get(`api/specifications/${this.goodsList[0].id}`, {
				'@expands': "['entity.product.category.type']"
			}).then((res) => {
				console.log('spec', res.data)
				if (res.data.product.__metadata.category.__metadata.type.__metadata.slug == 'PointCategory') {
					this.isPoint = true
					this.payType = 'point'
					this.request.get(`api/options/POINT_EXCHANGE_RATE`).then((res) => {
						this.pointRate = parseFloat(res.data.value)
					})
				}
			})
			this.getOrderCalculatePrice()
			this.request.get(`api/balances`).then((res) => {
				console.log('balance', res.data)
				this.point = res.data.point
				this.amount = res.data.amount
			})

		},
		computed: {},
		methods: {
			chooseAddress() {
				uni.chooseAddress({
					success: (res) => {
						this.selectedAddress = res
						console.log('address', res)
					},
					fail: (err) => {
						console.log(err)
						uni.showToast({
							title: '获取地址失败',
							icon: 'none'
						})
					}
				})
			},
			changeCurrent(e) {
				this.current = e
			},
			createOrder() {
				if (this.selectedAddress == '' && this.current == 0) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return
				}
				if (this.isPoint && (parseFloat(this.point) * this.pointRate - this.totalPrice) < 0) {
					uni.showToast({
						title: '积分不足!',
						icon: 'none'
					})
					return
				} 
				if(this.isPoint == false && this.payType == 'balance' && parseFloat(this.amount) - parseFloat(this.totalPrice) < 0){
					uni.showToast({
						title: '余额不足!',
						icon: 'none'
					})
					return
				}
				if(this.payType == 'point'){
					pointPaid = this.point
				}
				uni.showLoading()
				let items = []
				for (let i of this.goodsList) {
					items.push({
						specification: i.id,
						quantity: i.quantity
					})
				}
				let orderData = {
					store: 1,
					name: this.selectedAddress.userName,
					phone: this.selectedAddress.telNumber,
					address: `${this.selectedAddress.provinceName} ${this.selectedAddress.cityName} ${this.selectedAddress.countyName} ${this.selectedAddress.detailInfo}`,
					items: items,
					provinceName: this.selectedAddress.provinceName,
					cityName: this.selectedAddress.cityName,
					countyName: this.selectedAddress.countyName,
					postalCode: this.selectedAddress.postalCode,
					comment: this.comment
				}
				if (this.selectedCoupon != '') {
					orderData['userCoupons'] = [this.selectedCoupon.id]
				}
				if (this.usePoint == true && this.pointPaid > 0) {
					orderData['paidPoint'] = this.pointPaid / this.pointRate
				}
				this.request.post(`api/orders`, orderData).then((res) => {
					if (res.data.invoice) {
						let invoiceId = res.data.invoice.id
						if(this.payType == 'wechat'){
							wechatPay(invoiceId).then((res) => {
								uni.hideLoading()
								uni.showModal({
									title: '',
									content: '支付成功！',
									showCancel: false,
									success: () => {
										uni.redirectTo({
											url: '/pages/mine/orders'
										})
									}
								})
							}).catch((err) => {
								uni.hideLoading()
								uni.showModal({
									title: '',
									content: '支付失败，请重试',
									showCancel: false,
									success: () => {
										uni.redirectTo({
											url: '/pages/mine/orders'
										})
									}
								})
							})
						} else if(this.payType == 'balance'){
							this.request.post(`api/invoices/${invoiceId}/pay/balance`)
								.then((res) => {
									uni.hideLoading()
									uni.showModal({
										title: '',
										content: '支付成功！',
										showCancel: false,
										success: () => {
											uni.redirectTo({
												url: '/pages/mine/orders'
											})
										}
									})
								})
						}
					} else {
						uni.hideLoading()
						uni.showModal({
							title: '',
							content: '支付成功！',
							showCancel: false,
							success: () => {
								uni.redirectTo({
									url: '/pages/mine/orders?type=point'
								})
							}
						})
					}

				})

			},
			// 计算价钱
			getOrderCalculatePrice() {
				uni.showLoading()
				let items = []
				for (let i of this.goodsList) {
					items.push({
						specification: i.id,
						quantity: i.quantity
					})
				}
				let orderData = {
					items: items
				}
				if (this.selectedAddress) {
					orderData['address'] =
						`${this.selectedAddress.provinceName}${this.selectedAddress.cityName}${this.selectedAddress.detailInfo}`
				}
				if (this.selectedCoupon != '') {
					orderData['userCoupons'] = [this.selectedCoupon.id]
				}
				console.log('order', orderData)
				this.request.post(`api/orders/calculate-prices`, orderData).then((res) => {
					console.log('订单返回数据', res.data)
					this.actualPrice = parseFloat(res.data.actualPrice) - this.pointDiscount
					this.totalPrice = parseFloat(res.data.totalPrice)
					this.discount = parseFloat(res.data.discount)
					this.orderItems = res.data.items
					uni.hideLoading()
				})
			},
		}
	}
</script>

<style>
	.checkout-page {
		padding-bottom: 120rpx;
	}

	.address-card {
		display: flex;
		align-items: center;
		padding: 30rpx;
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
	}

	.empty-address {
		display: flex;
		align-items: center;
		color: #999;
	}

	.address-info {
		flex: 1;
	}

	.address-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.address-detail {
		font-size: 26rpx;
		color: #666;
	}

	.goods-section {
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.section-title {
		font-weight: bold;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.goods-item {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.goods-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 28rpx;
		line-height: 1.4;
	}

	.goods-spec {
		font-size: 24rpx;
		color: #999;
	}

	.goods-bottom {
		display: flex;
		justify-content: space-between;
	}

	.goods-price {
		color: #f40;
		font-weight: bold;
	}

	.coupon-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
	}

	.coupon-right {
		/* display: flex; */
		align-items: center;
	}

	.coupon-selected {
		color: #f40;
		margin-right: 10rpx;
	}

	.price-section {
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		padding: 15rpx 0;
	}

	.price-row.total {
		border-top: 1rpx solid #eee;
		margin-top: 10rpx;
		padding-top: 20rpx;
	}

	.price-total {
		color: #f40;
		font-size: 36rpx;
		font-weight: bold;
	}

	/* .footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  width: 100%;
} */
	.pay-btn {
		background: #f40;
		color: #fff;
		border-radius: 50rpx;
		width: 250rpx;
	}

	.coupon-popup {
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
		max-height: 70vh;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
		font-weight: bold;
	}

	.coupon-list {
		max-height: 60vh;
		padding-top: 20rpx;
	}

	.coupon-item {
		display: flex;
		padding: 25rpx;
		margin-bottom: 20rpx;
		background: #fff9f0;
		border-radius: 12rpx;
		position: relative;
	}

	.coupon-left {
		border-right: 1rpx dashed #ffd591;
		padding-right: 20rpx;
		margin-right: 20rpx;
	}

	.coupon-value {
		color: #f40;
		font-size: 36rpx;
		font-weight: bold;
	}

	.coupon-condition {
		font-size: 24rpx;
		color: #999;
	}

	.coupon-selected-icon {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
	}
</style>